package com.inventory.controllers;

import com.inventory.entities.Item;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * ItemControllerBean handles all the 
 * @author sithum
 */
@Stateless(mappedName="ItemController")
public class ItemControllerBean implements ItemControllerRemote {
    
    /*
     * Injects the specified Persistence unit to the EntityManager associated
     * with the current transaction.
     */
    @PersistenceContext(unitName = "SaicssPU")
    private EntityManager em;

    /**
     * Create new records in the Item relation in the database.
     * @param itemList
     */
    public void create(List<Item> itemList){
        for (Item item : itemList){
            em.persist(item);
        }
    }

    /**
     * Updates an existing list of items in the database.
     * @param itemList
     */
    public void edit(List<Item> itemList){
        for (Item item : itemList) {
            em.persist(em.merge(item));
        }
    }

    /**
     * Removes existing set of records.
     * @param itemList
     */
    public void delete(List<Item> itemList){
        for (Item item : itemList){
            em.remove(em.merge(item));
        }
    }

    public List<Item> findAll(){
        return em.createNamedQuery("Item.findAll").getResultList();
    }

    public int count(){
        Query count = em.createNamedQuery("Item.recordCount");
        return Integer.valueOf(count.getSingleResult().toString()).intValue();
    }
 
}
